import { iup } from '../../util';
import {
  attachDataRes,
  attachDeleteParams,
  attachLabelSaveParams,
  attachListDataRes,
  attachSaveParams,
  createZipParams,
  downloadFileParams,
  getAttachListParams,
  getDownLoadHistoryParams,
  getPreviewUrlParams,
  getTempAttachmentParams,
  getZipDownloadInfoParams,
  tableAttachSaveRemarkParams,
  uploadFileParams
} from './type';
import { customRequest, getFileCenterApiUrl } from './util';

const adaptorData = (data: attachDataRes[] = []) => {
  return data.map((item) => {
    return {
      approved: 0, // 审批字段，未使用
      asrFid: item.fileId, // 唯一确定一个附件
      asrName: item.fileName, // 附件名称
      asrFlag: item.status, // 附件状态, 0 未保存 1 已保存
      asrRemark: item.remark, // 备注
      asrSize: item.fileSize, // 附件大小,无需转换直接展示
      originFileSize: Number(item.originFileSize || 0), // 原始文件大小
      userName: item.uploadName, // 上传人
      asrFilldt: item.createTime, // 上传时间
      userId: item.createId, // 上传人id
      asrTable: item.tag, // TODO busiId 跟附件关联的单据的 表名称  asrTable 变为 tag
      asrCode: item.busiId, // 唯一确定一个单据
      label: item.label // 附件标签
    };
  });
};

const filterUndefined = (data) => {
  const obj = {};
  Object.keys(data).forEach((key) => {
    if (data[key] !== undefined) {
      obj[key] = data[key];
    }
  });
  return obj;
};

/**
 * 表格附件初始化接口（加载附件时调用）
 */
const defaultPreviewFileType = ['png', 'jpg', 'jpeg', 'xls', 'xlsx', 'doc', 'docx', 'ppt', 'pptx', 'pdf', 'ofd', 'mp4'];
export async function tableAttachInit(data: getAttachListParams, cancelId?: string) {
  const { absUrl, url } = getFileCenterApiUrl('/iup-file/tripartite/list');
  const res = await customRequest.get({
    absUrl,
    url,
    data: filterUndefined(data),
    cancel: cancelId
  });
  if (res?.code === 0) {
    const previewFileType = res.previewFileType ? (res.previewFileType as string).split('.') : defaultPreviewFileType;
    return {
      cursorId: res?.data?.cursorId,
      fileWhiteList: res?.data?.accept?.fileWhiteList,
      fileBlackList: res?.data?.accept?.fileBlackList,
      specialChars: res?.data?.accept?.specialChars,
      previewFileType,
      data: adaptorData(res?.data?.data)
    } as attachListDataRes;
  } else {
    throw new Error(res?.message);
  }
}

/**
 * 获取临时附件
 */
export async function getTempAttachment(data: getTempAttachmentParams) {
  try {
    const { absUrl, url } = getFileCenterApiUrl('/iup-file/tripartite/list-cursor');
    const res = await customRequest.get({
      absUrl,
      url,
      data: filterUndefined(data)
    });
    if (res?.code === 0) {
      return adaptorData(res?.data);
    }
  } catch (e) {
    console.log(e);
  }
  return [];
}

/**
 * 文件分片上传
 */
export async function uploadFile(data: uploadFileParams) {
  const formData = new FormData();
  Object.keys(data).forEach((key) => {
    if (data[key] !== undefined) {
      if (key === 'file') {
        formData.append(key, data[key], data['fileName']);
      } else {
        formData.append(key, data[key]);
      }
    }
  });
  const { absUrl, url } = getFileCenterApiUrl('/iup-file/tripartite/upload-big-file');
  return await customRequest.post({
    absUrl,
    url,
    data: formData
  });
}
export async function richUploadFile(data: uploadFileParams, userToken = iup.getUser().accessToken) {
  const formData = new FormData();
  Object.keys(filterUndefined(data)).forEach((key) => {
    if (key === 'file') {
      formData.append(key, data[key], data['fileName']);
    } else {
      formData.append(key, data[key]);
    }
  });
  const { absUrl, url } = getFileCenterApiUrl('/iup-file/tripartite/rich-text-upload');
  try {
    return await customRequest.post({
      absUrl,
      url,
      headers: { 'User-Token': userToken },
      data: formData
    });
  } catch (e) {
    console.log(e);
  }
  return null;
}

/**
 * 获取文件链接
 */
export async function getPreviewUrl(data: getPreviewUrlParams) {
  try {
    const { absUrl, url } = getFileCenterApiUrl('/iup-file/tripartite/preview-url');
    return await customRequest.get({
      absUrl,
      url,
      data
    });
  } catch (e) {
    console.log(e);
  }
  return null;
}

/**
 * 下载文件
 */
export async function getDownloadFileUrl(data: downloadFileParams) {
  try {
    const { absUrl, url } = getFileCenterApiUrl('/iup-file/tripartite/download-url');
    return await customRequest.get({
      absUrl,
      url,
      data
    });
  } catch (e) {
    console.log(e);
  }
  return null;
}

/**
 * 附件上传接口（分块上传，分块大小1M）
 */
export async function attachUpload(data, dbToken = iup.getUser().ucode) {
  try {
    return await customRequest.post({
      url: '/JFileSrv/file/newUpload',
      headers: { dbToken },
      data
    });
  } catch (e) {
    console.log(e);
  }
  return null;
}

/**
 * 附件删除接口
 */
export async function attachDelete(data: attachDeleteParams) {
  try {
    const { absUrl, url } = getFileCenterApiUrl('/iup-file/tripartite/del');
    return iup.request.delete({
      absUrl,
      url,
      data
    });
  } catch (e) {
    console.log(e);
  }
  return null;
}

/**
 * 附件保存接口
 */
export async function attachSave(data: attachSaveParams[]) {
  const { absUrl, url } = getFileCenterApiUrl('/iup-file/tripartite/busi-type-bind');
  return await customRequest.body({
    absUrl,
    url,
    data: filterUndefined(data)
  });
}

/**
 * 附件获取下载信息接口（调用下载接口前调用）
 */
export async function attachGetDownloadInfo(data, dbToken = iup.getUser().ucode) {
  try {
    return await customRequest.get({
      url: '/JFileSrv/reactAttach/getDownloadInfo',
      headers: { dbToken },
      data
    });
  } catch (e) {
    console.log(e);
  }
  return null;
}
/**
 * 附件下载接口
 */
export async function attachDownload(data, dbToken = iup.getUser().ucode) {
  try {
    return await customRequest.get({
      url: '/JFileSrv/file/download',
      //  url: 'http://10.18.44.11:30599/JFileSrv/file/download',
      //  absUrl: true,
      headers: { dbToken },
      responseType: 'arrayBuffer',
      data
    });
  } catch (e) {
    console.log(e);
  }
  return null;
}

/**
 * 附件获取下载水印文件信息接口（下载水印文件接口前调用）
 */
export async function attachGetDownloadWaterMarkInfo(data, dbToken = iup.getUser().ucode) {
  try {
    return await customRequest.get({
      url: '/JFileSrv/watermark/getWaterMarkFileForReact',
      headers: { dbToken },
      data
    });
  } catch (e) {
    console.log(e);
  }
  return null;
}

/**
 * 附件下载水印接口
 */
export async function attachDownloadWaterMarkFile(data, dbToken = iup.getUser().ucode) {
  try {
    return await customRequest.get({
      url: '/JFileSrv/watermark/downloadWaterMarkFile',
      headers: { dbToken },
      responseType: 'arrayBuffer',
      data
    });
  } catch (e) {
    console.log(e);
  }
  return null;
}

/**
 * 获取水印内容接口
 */
export async function attachGetWaterMarkContent(data, dbToken = iup.getUser().ucode) {
  try {
    return await customRequest.get({
      url: '/JFileSrv/watermark/getWaterMarkContentForReact',
      headers: { dbToken },
      data
    });
  } catch (e) {
    console.log(e);
  }
  return null;
}

/**
 * 表格附件修改备注接口
 */
export async function tableAttachSaveRemark(data: tableAttachSaveRemarkParams) {
  try {
    const { absUrl, url } = getFileCenterApiUrl('/iup-file/tripartite/remark');
    return await iup.request.put({
      absUrl,
      url,
      data
    });
  } catch (e) {
    console.log(e);
  }
  return null;
}

/**
 * 附件修改标签接口
 */
export async function saveAttachLabel(data: attachLabelSaveParams) {
  try {
    const { absUrl, url } = getFileCenterApiUrl('/iup-file/tripartite/save-update-label');
    return await iup.request.body({
      absUrl,
      url,
      data
    });
  } catch (e) {
    console.log(e);
  }
  return null;
}

/**
 * 工作流附件取数参数获取接口
 */
export async function getTaskAttachmentParams(data, dbToken = iup.getUser().ucode) {
  try {
    return await customRequest.get({
      url: '/api/WorkFlow3/WorkFlowApp/GetTaskAttachment',
      headers: { Authorization: iup.getUser().ucode ?? dbToken },
      data
    });
  } catch (e) {
    console.log(e);
  }
  return null;
}

/**
 * 来源单据附件取数参数获取接口
 */
export async function getBillSourceAttachmentParams(data, dbToken = iup.getUser().ucode) {
  try {
    return await customRequest.get({
      url: '/api/IMP/EngineApi/GetBillSourceInfo',
      headers: { Authorization: iup.getUser().ucode ?? dbToken },
      data
    });
  } catch (e) {
    console.log(e);
  }
  return null;
}

/**
 * 获取下载记录接口
 */
export async function getDownLoadList(data: getDownLoadHistoryParams) {
  try {
    const { absUrl, url } = getFileCenterApiUrl('/iup-file/down-his/list');
    return await customRequest.get({
      absUrl,
      url,
      data
    });
  } catch (e) {
    console.log(e);
  }
  return null;
}

/**
 * 保存标签接口
 */
export async function saveTags(data, dbToken = iup.getUser().ucode) {
  try {
    return await customRequest.post({
      url: '/JFileSrv/reactAttach/docTagsSave',
      headers: { dbToken },
      data
    });
  } catch (e) {
    console.log(e);
  }
  return null;
}

/**
 * 共享保存接口
 */
export async function shareSave(data, dbToken = iup.getUser().ucode) {
  try {
    return await customRequest.post({
      url: '/JFileSrv/reactAttach/saveAttachShare',
      headers: { dbToken },
      data
    });
  } catch (e) {
    console.log(e);
  }
  return null;
}

/**
 * 创建打包任务接口
 */
export async function createZip(data: createZipParams) {
  try {
    const { absUrl, url } = getFileCenterApiUrl('/iup-file/tripartite/zip/task');
    return await customRequest.get({
      absUrl,
      url,
      data
    });
  } catch (e) {
    console.log(e);
  }
  return null;
}

/**
 * 获取压缩包下载信息接口
 */
export async function getZipDownloadInfo(data: getZipDownloadInfoParams) {
  try {
    const { absUrl, url } = getFileCenterApiUrl(`/iup-file/tripartite/zip/task/progress/${data.id}`);
    return await customRequest.get({
      absUrl,
      url
    });
  } catch (e) {
    console.log(e);
  }
  return null;
}

/**
 * 修改分类接口
 */
export async function editCategory(data, dbToken = iup.getUser().ucode) {
  try {
    return await customRequest.post({
      url: '/JFileSrv/attachtype/modifyAttachType',
      headers: { dbToken },
      data
    });
  } catch (e) {
    console.log(e);
  }
  return null;
}

/**
 * 获取附件预览列表
 */
export async function getPreviewAttachmentList(data, dbToken = iup.getUser().ucode) {
  try {
    return await customRequest.body({
      url: '/JFileSrv/file/previewBatch',
      headers: { dbToken },
      data
    });
  } catch (e) {
    console.log(e);
  }
  return null;
}

/**
 * 获取单据审批流状态
 */
export async function getAttachmentAuditStatus(data, dbToken = iup.getUser().ucode) {
  try {
    return await customRequest.get({
      url: '/SUP/Attachment/AttachmentGetAuditStatus',
      headers: { dbToken },
      data
    });
  } catch (e) {
    console.log(e);
  }
  return null;
}

/**
 * 获取单据审批流状态
 */
export async function getAttachmentCountBatch(data, dbToken = iup.getUser().ucode) {
  try {
    return await customRequest.body({
      url: '/fileSrv/record/attachmentRecord/getCountBatch',
      headers: { dbToken },
      data
    });
  } catch (e) {
    console.log(e);
  }
  return null;
}

export async function mergeChunks(data: { cursorId: string; totalChunks: number; md5: string; busiType: string }) {
  const { absUrl, url } = getFileCenterApiUrl('/iup-file/tripartite/merge');
  const res = await customRequest.body({
    absUrl,
    url,
    data
  });
  if (Number(res?.code) === 0) {
    return {
      fileId: res.data.fileId as string | undefined,
      failedChunks: res.data.list as number[] | undefined
    };
  } else {
    throw new Error(res?.message);
  }
}
